package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.AdminConstants;
import com.heima.common.exception.ExceptionCatch.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1.校验参数
        dto.checkParam();
        //2.执行查询
        //2.1分页条件
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //2.2查询条件
        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            lambdaQuery.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> result = this.page(page, lambdaQuery);
        //3.将分页结果封装
        return new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), result
                .getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 30000)
//    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验信息 校验参数
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证id不能为空");
        }
        //根据实名认证的id查询实名认证的信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息不存在");
        }
        //判断实名认证的状态
        if (!AdminConstants.WAIT_AUTH.equals(dto.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证状态不是待审核");
        }
        //根据实名认证关联的userid 查询apuser对象信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "未发现实名认证的apuser信息");
        }
        //2.修改实名状态
        apUserRealname
                .setStatus(status);
        apUserRealname
                .setReason(dto.getMsg());
        this.updateById(apUserRealname);
        //3如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //3.1开通自媒体
            WmUser wmUser = creatWmUser(apUser);

            //3.2开通作者
            createApAuthor(wmUser);
        }
        return ResponseResult.okResult();
    }

    @Autowired ArticleFeign articleFeign;

    private void createApAuthor(WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        //4. 结果失败，抛出异常
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    //远程开通自媒体账户
    private WmUser creatWmUser(ApUser apUser) {
        //根据用户名查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser!=null){
        //如果有用户抛出异常用户已存在
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体用户已存在开通失败");
        }
        //如果没有用户创建该用户
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        //远程保存自媒体用户

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }


}
